/**
 * 异步分页请求数据并拼合排序
 */

const https = require('https');


// Promise封装请求
function fetchUrl(url){
	return new Promise((resolve,reject)=>{
		https.get(url, res => {
			let data = '';

			res.on('data',chunck=>{
				data += chunck;
			})

			res.on('end',()=>{
				resolve(JSON.parse(data))
			})
		}).on('error',err=>{
			reject(err)
		})
	})
}

// 字符串数组首字母排序
function sortStrArr(strArr){
	const res = strArr.sort((a,b)=>  a.substr(0,1).localeCompare(b.substr(0,1)));
	return res;
}


/* 测试字符串数组排序 */
// const strArr = ['Ifsdhfjsdhf','Cfncsdf','Dnnfndsaf','Afsdjfiuqwrnjdkf'];
// sortStrArr(strArr);


// https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman&page=1

function getResponse(moveName){
	const res = [];
	const resPromises = [];
	let pages = 1;

	fetchUrl(`https://jsonmock.hackerrank.com/api/movies/search/?Title=${moveName}&page=${pages}`).then( response=>{
		[].push.apply(res,response.data);
		pages = response.total_pages;
		console.log('pages',pages)

		while(pages>=2){
			const resPromise = fetchUrl(`https://jsonmock.hackerrank.com/api/movies/search/?Title=${moveName}&page=${pages}`)
			resPromises.push(resPromise)
			pages--;
		}

		Promise.all(resPromises).then(data=>{
			data.forEach(pageItem => {
				[].push.apply(res,pageItem.data);
			})
			console.log(sortStrArr(res.map(v=>v.Title)));	//结果
		})



	})
}

getResponse('spiderman');

// 输出结果，已按照首字母排序
/*
	[ 'Amazing Spiderman Syndrome',
  'Fighting, Flying and Driving: The Stunts of Spiderman 3',
  'Hollywood\'s Master Storytellers: Spiderman Live',
  'Italian Spiderman',
  'Spiderman in Cannes',
  'Spiderman and Grandma',
  'Superman, Spiderman or Batman',
  'Spiderman',
  'Spiderman',
  'Spiderman 5',
  'They Call Me Spiderman',
  'The Death of Spiderman',
  'The Amazing Spiderman T4 Premiere Special' ]
*/






